import requests
import json
import yaml

class Litemall:
    def login(self, username, password):
        r = requests.post(
            'https://litemall.hogwarts.ceshiren.com/wx/auth/login',
            headers={'Content-Type': 'application/json;charset=UTF-8'},
            json={
                'username': username,
                'password': password,
            },
        )

        token = r.json()['data']['token']
        self.token = token
        return r

    def test_write_yaml(self):
        # print(self.token,'123')
        t_data = {
            "token": self.token
        }
        # print(t_data,'3333')
        with open("../data/token.yaml ", "w", encoding="utf-8") as f:
            a = yaml.safe_dump(data=t_data, stream=f, allow_unicode=True)
            # print(type(a))
            f.write(a)

    def search_list(self, keyword, page, limit, categoryId):
        print(keyword,page,limit,categoryId,'123456')
        r = requests.get(
            'https://litemall.hogwarts.ceshiren.com/wx/goods/list',
            params={'keyword': keyword, 'page': page, 'limit': limit, 'categoryId': categoryId},
            headers={'Content-Type': 'application/json;charset=UTF-8'}
        )
        # assert r.status_code == 200
        # assert r.json()['errno'] == 0
        goods_id = r.json()['data']['list'][0]['id']
        # print(str(goods_id))
        return str(goods_id)

    def goods_detail(self, goods_id):

        print(goods_id, '44444')
        r = requests.get(
            'https://litemall.hogwarts.ceshiren.com/wx/goods/detail', params={'id': goods_id},
            headers={'Content-Type': 'application/json;charset=UTF-8'}
        )

        # assert r.status_code == 200
        # assert r.json()['errno'] == 0
        productId = r.json()['data']['productList'][0]['id']
        # print(productId)
        return str(productId)

    def add_cart(self, goods_id, productId):
        # goods_id = self.search_list()
        # productId = self.goods_detail()
        r = requests.post(
            'https://litemall.hogwarts.ceshiren.com/wx/cart/add',
            headers={'Content-Type': 'application/json;charset=UTF-8',
                     'X-Litemall-Token': self.token},
            json={
                'goodsId': int(goods_id),
                'number': 1,
                'productId': int(productId),
            },
        )
        return r

    def cart_list(self):
        r = requests.get(
            "https://litemall.hogwarts.ceshiren.com/wx/cart/index",
            headers={'Content-Type': 'application/json;charset=UTF-8',
                     'X-Litemall-Token': self.token},
            params={'': ''})
        print(r.apparent_encoding)
        return r





